<template>
  <div class="menu-manage-page">
    <div class="main">
      <div class="header">
        <p class="title">
          功能模块管理（{{ projectInfo.projectAbbreviation || projectInfo.projectName || '' }}）
        </p>
        <div class="search-container">
          <div class="search-input">
            <el-input placeholder="模块名称" v-model="condition"></el-input>
            <el-button class="search-btn" type="primary" @click="handleSearch">
              <i class="el-icon-search"></i>
            </el-button>
            <el-button type="primary" @click="handleRefresh">
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="btns">
            <el-button @click="$router.back()">
              返回
            </el-button>
            <el-button v-if="hasTabSet" type="primary" :loading="loading" @click="handleSave">
              授权
            </el-button>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="menu-type">
          <div class="menu-title">
            <span>菜单类型</span>
          </div>
          <ul>
            <li
              v-for="item in menuTypes"
              :class="classId === item.id ? 'active' : ''"
              :key="item.id"
              @click="handleClick(item.id)">
              {{ item.className }}
            </li>
          </ul>
        </div>
        <div class="table-container">
          <el-table
            v-loading="tableLoading"
            :data="tableData"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            row-key="id">
            <el-table-column prop="select" width="100">
              <template slot="header" slot-scope="scope">
                <el-checkbox
                  :value="hasSelected"
                  @change="selectAll">
                </el-checkbox>
              </template>
              <template slot-scope="scope">
                <el-checkbox
                  true-label="1"
                  false-label="0"
                  :value="scope.row.isCheck"
                  @change="(val) => handleChange(val, scope.row)">
                </el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column prop="name" label="菜单名称"></el-table-column>
            <el-table-column prop="path" label="地址"></el-table-column>
            <el-table-column prop="icon" label="图标">
              <template slot-scope="scope">
                <i v-if="scope.row.icon" class="iconfont">{{ setIcon(scope.row.icon) }}</i>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型">
              <template slot-scope="scope">
                {{ types[scope.row.type] || '' }}
              </template>
            </el-table-column>
            <div class="empty-content" slot="empty">
              <i class="iconfont iconwushuju"></i>
              <p>暂无数据</p>
            </div>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      projectId: '',
      condition: '',
      projectInfo: {},
      selectIds: [],
      hasSelected: false,
      loading: false,
      menuTypes: [],
      classId: '',
      hasSearch: false,
      tableData: [],
      tableIds: [],
      tableLoading: false,
      types: {
        '0': '目录',
        '1': '菜单',
        '2': '按钮'
      },
    };
  },
  async created() {
    this.projectId = this.$route.query.id || '';
    this.getByProjectId();
    this.getIconList();
    await this.getProjectTree();
    this.getMenuClass();
  },
  methods: {
    // 获取项目详情
    async getByProjectId() {
      if (!this.projectId) return;
      const params = {
        projectId: this.projectId,
      };
      const { success, data: {
        data
      }} = await this.$Model.getByProjectId(params);
      if (success && data) {
        this.projectInfo = data;
      }
    },
    /**
     * 获取项目菜单权限
     */
    async getProjectTree() {
      if (!this.projectId) return;
      const { success, data: {
        data
      }} = await this.$Model.getProjectTree({
        id: this.projectId
      });
      if (success) {
        this.selectIds = this.getSelectIds(data);
      }
    },
    /**
     * 获取菜单
     */
    async getTableData() {
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getMenuTree({
        classId: this.classId
      });
      this.tableLoading = false;
      if (success) {
        this.tableData = this.setTreeData(data);
        this.tableIds = this.setTableIds(data);
        this.checkAll();
      }
    },
    /**
     * 获取菜单分类
     */
    async getMenuClass() {
      const { success, data: {
        data
      }} = await this.$Model.getMenuClass({
        pageFlag: false,
        condition: this.hasSearch ? this.condition : ''
      });
      if (success && data) {
        this.menuTypes = data.list || [];
        if (!this.classId) {
          this.classId = this.menuTypes[0]
            ? this.menuTypes[0].id
            : '';
          this.getTableData();
        }
      }
    },
    // 获取所授权的ID
    getSelectIds(data = [], keys = []) {
      const result = keys;
      data && data.forEach(item => {
        const { children, isCheck, id } = item;
        if (isCheck === '1') result.push(id);
        if (children && children.length) {
          this.getSelectIds(children, result);
        }
      });
      return result;
    },
    // 获取当前列表所有ID
    setTableIds(data, keys = []) {
      const ids = keys;
      data && data.forEach(item => {
        const { children, id } = item;
        ids.push(id);
        if (Array.isArray(children) && children.length) {
          this.setTableIds(children, ids);
        }
      });
      return ids;
    },
    checkId(id) {
      return this.selectIds.includes(id) ? '1' : '0';
    },
    // 校验全选
    checkAll() {
      this.hasSelected = this.tableIds.every(id => (
        this.selectIds.includes(id)
      ));
    },
    /**
     * 设置菜单勾选状态
     * @param {Array} data 当前菜单数据
     * @param {?String} type
     * @param {?Boolean} selected 是否全选
     */
    setTreeData(data = [], type, selected) {
      return data && data.map(item => {
        const { children, id } = item;
        let isCheck = selected ? '1' : '0';
        if (type === 'all') {
          const index = this.selectIds.indexOf(id);
          if (selected) {
            index === -1 && this.selectIds.push(id);
          } else {
            index > -1 && this.selectIds.splice(index, 1);
          }
        } else {
          isCheck = this.checkId(id);
        }
        return {
          ...item,
          isCheck,
          children: this.setTreeData(children, type, selected)
        };
      }) || [];
    },
    // 获取icon图标
    getIconList() {
      try {
      /* eslint-disable */
        this.$axios.get(this.$configs.iconJson).then(res => {
          if (res && res.status === 200 && res.data) {
            const glyphs = res.data.glyphs || [];
            this.iconList = glyphs.map(item => ({
              ...item,
              iconStr: eval("'" + `\\u${item.unicode}` + "'")
            }));
          }
        });
      } catch (e) {}
    },
    // 设置icon图标
    setIcon(iconId) {
      const item = this.iconList.find(v => v.icon_id === iconId);
      return item ? item.iconStr : '';
    },
    handleSearch() {
      this.hasSearch = true;
      this.getMenuClass();
    },
    handleRefresh() {
      this.hasSearch = false;
      this.condition = '';
      this.getMenuClass();
    },
    // 切换菜单分类
    handleClick(id) {
      this.classId = id;
      this.getTableData();
    },
    // 全选
    selectAll(hasCheck) {
      this.hasSelected = hasCheck;
      this.tableData = this.setTreeData(this.tableData, 'all', hasCheck);
    },
    // 勾选菜单
    handleChange(val, row) {
      this.setCheck(val, row);
      this.tableData = this.setTreeData(this.tableData);
      if (val === '1') { // 选中
        this.checkAll();
        return;
      }
      this.hasSelected = false;
    },
    // 设置勾选
    setCheck(val, row) {
      const { id, children } = row;
      const hasCheck = val === '1'; // 是否选中
      const index = this.selectIds.indexOf(id);
      if (hasCheck) {
        index < 0 && this.selectIds.push(id);
      } else {
        index > -1 && this.selectIds.splice(index, 1);
      }
      if (Array.isArray(children) && children.length) {
        children.forEach(item => this.setCheck(val, item));
      }
    },
    // 授权
    async handleSave() {
      this.loading = true;
      const { success } = await this.$Model.setProjectPermissions({
        projectId: this.projectId,
        sysProjectPermissions: this.selectIds.map(id => ({
          menuId: id,
          projectId: this.projectId
        }))
      });
      this.loading = false;
      if (success) {
        this.$message.success('授权成功');
        this.getProjectTree();
      }
    },
  }
};
</script>

<style scoped lang="scss">
  @import "../../assets/styles/table";
  @import "../../assets/styles/dialog";

  .menu-manage-page {
    width: 100%;
    height: 100%;
    padding: 20px 30px;
    background-color: $baseBg;
    .main {
      width: 100%;
      height: 100%;
      padding: 20px;
      background-color: $mainBg;
      .header {
        width: 100%;
        height: 100px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-bottom: 20px;
        .title {
          font-size: 20px;
        }
        .search-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .search-input {
            display: flex;
            .tabs {
              display: flex;
              margin-right: 20px;
              box-shadow: 0 0 3px 0 $mainBg;
              li {
                width: 120px;
                background: #fff;
                color: rgba(0, 0, 0, .8);
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                transition: all .2s;
                &.active, &:hover {
                  background: $linearG;
                  color: #fff;
                }
                &:nth-child(1) {
                  border-radius: 5px 0 0 5px;
                }
                &:nth-last-child(1) {
                  border-radius: 0 5px 5px 0;
                }
              }
            }
            .el-input {
              width: 260px;
              margin-right: 20px;
            }
          }
        }
        .btns {
          .upload-file {
            position: relative;
            cursor: pointer;
            .file {
              position: absolute;
              width: 100%;
              height: 100%;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              opacity: 0;
              cursor: pointer;
            }
          }
        }
      }
      .content {
        width: 100%;
        height: calc(100% - 100px);
        display: flex;
        justify-content: space-between;
        .menu-type {
          width: 300px;
          height: calc(100% - 20px);
          padding-right: 20px;
          border-right: 1px dotted #fff;
          .menu-title {
            height: 40px;
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            span {
              font-size: 18px;
            }
            i {
              margin-left: 10px;
              width: 25px;
              height: 25px;
              text-align: center;
              line-height: 25px;
              background-color: rgba(160, 164, 179, 0.4);
              border-radius: 5px;
              cursor: pointer;
              &:hover {
                color: $lightBtnBg;
              }
            }
          }
          ul {
            height: calc(100% - 40px);
            width: 100%;
            overflow-y: auto;
            li {
              height: 40px;
              width: 100%;
              text-align: center;
              line-height: 40px;
              color: #fff;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              margin-bottom: 20px;
              background-color: $lightBtnBg;
              transition: all .2s;
              border-radius: 5px;
              border: 1px solid transparent;
              cursor: pointer;
              &:hover, &.active {
                color: $mainColor;
                background-color: $mainBtnBg;
                border-color: $lightBtnBg;
              }
            }
          }
        }
        .table-container {
          width: calc(100% - 320px);
          height: 100%;
          /deep/ .el-table {
            height: calc(100% - 50px);
            .el-table__body-wrapper {
              height: calc(100% - 40px);
              overflow-y: auto;
              .btn {
                color: $mainColor;
                cursor: pointer;
                &:hover {
                  text-decoration: underline;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
